﻿#include "firststartdialog.h"
#include "ui_firststartdialog.h"
#include <QDebug>
#include "flatui.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QMessageBox>
#include "nettools.h"
#include <QSettings>
#include <QMessageBox>
#include <QCryptographicHash>
#include "loginwindow.h"
#include "dbtools.h"
#include <QProcess>
FirstStartDialog::FirstStartDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FirstStartDialog)
{
    ui->setupUi(this);


    ui->lineEditMainPass->setFocus();

    setFixedHeight(200);
    setWindowTitle("初始化设置");
    this->setWindowIcon(QPixmap(":/new/prefix1/res/w128X128.ico"));
    ui->groupBox_2->setVisible(false);
    ui->groupBox_3->setVisible(false);
    ui->pushButtonBindCloudAccout->setFixedWidth(80);
    ui->pushButtonTestServer->setFixedWidth(80);
    ui->pushButtonCancel->setFixedWidth(80);
    ui->pushButtonOk->setFixedWidth(80);

    initStyle();
    initEvent();

}

FirstStartDialog::~FirstStartDialog()
{
    delete ui;
}

void FirstStartDialog::on_checkBoxUseSky_stateChanged(int arg1)
{
    if(ui->checkBoxUseSky->isChecked()){
        ui->groupBox_2->setVisible(true);
        this->setFixedHeight(500);
        ui->groupBox_3->setVisible(true);
        this->move(this->frameGeometry().x(),this->frameGeometry().y()-100);

    }else{
        this->setFixedHeight(200);
        ui->groupBox_2->setVisible(false);
        ui->groupBox_3->setVisible(false);
        this->move(this->frameGeometry().x(),this->frameGeometry().y()+100);
    }
}

void FirstStartDialog::on_checkBoxUseNetProxy_stateChanged(int arg1)
{
    if(ui->checkBoxUseNetProxy->isChecked()){

        qDebug()<<"启用代理";
        QString server = ui->lineEditProxyServer->text().trimmed();
        int port = ui->lineEditProxyPort->text().trimmed().toInt();
        QString user = ui->lineEditProxyUsername->text().trimmed();
        QString pass = ui->lineEditProxyPassword->text();
        if(server.isEmpty()){
            ui->labelProxyMsg->setText("<span style='color:red;'>服务器地址不能为空!</span>");
            ui->checkBoxUseNetProxy->setChecked(false);
            return;
        }
        if(port<=0){
            ui->labelProxyMsg->setText("<span style='color:red;'>端口不能为空!</span>");
            ui->checkBoxUseNetProxy->setChecked(false);
            return;
        }
        QNetworkProxy proxy;
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(server);
        proxy.setPort(port);
        if(!user.isEmpty()){
            proxy.setUser(user);
        }
        if(!pass.isEmpty()){
            proxy.setPassword(pass);
        }
        QNetworkProxy::setApplicationProxy(proxy);

        //保存代理信息
        QSettings setting;
        setting.setValue("network/proxy/server",server);
        setting.setValue("network/proxy/port",port);
        setting.setValue("network/proxy/user",user);
        setting.setValue("network/proxy/pass",pass);

    }else{
        QNetworkProxy proxy;
        QNetworkProxy::setApplicationProxy(proxy);
        qDebug()<<"停用代理";
    }
}

void FirstStartDialog::initStyle()
{
    FlatUI::Instance()->setLineEditQss(ui->lineEditMainPass);
    FlatUI::Instance()->setLineEditQss(ui->lineEditServerAddr);
    FlatUI::Instance()->setLineEditQss(ui->lineEditCloudAccout);
    FlatUI::Instance()->setLineEditQss(ui->lineEditProxyServer);
    FlatUI::Instance()->setLineEditQss(ui->lineEditProxyPort);
    FlatUI::Instance()->setLineEditQss(ui->lineEditProxyUsername);
    FlatUI::Instance()->setLineEditQss(ui->lineEditProxyPassword);
    FlatUI::Instance()->setPushButtonQss(ui->pushButtonBindCloudAccout,5, 8,
                                         "#3498DB", "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
    FlatUI::Instance()->setPushButtonQss(ui->pushButtonCancel);
    FlatUI::Instance()->setPushButtonQss(ui->pushButtonOk,5, 8,
                                         "#1ABC9C", "#E6F8F5", "#2EE1C1", "#FFFFFF", "#16A086", "#A7EEE6");
    FlatUI::Instance()->setPushButtonQss(ui->pushButtonTestServer,5, 8,
                                         "#3498DB", "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
}

void FirstStartDialog::initEvent()
{

}

void FirstStartDialog::on_pushButtonTestServer_clicked()
{
    QString server = ui->lineEditServerAddr->text().trimmed();
    if(server.isEmpty()){
        QMessageBox::critical(this,"错误","服务器地址不能为空！",QMessageBox::Ok,QMessageBox::Ok);
        return;
    }
    NetTools *net = new NetTools;
    connect(net,SIGNAL(testServerResult(bool,QString)),this,SLOT(testServerResult(bool,QString)));


    net->testServer(server);
}

void FirstStartDialog::on_pushButtonBindCloudAccout_clicked()
{
    QString account = ui->lineEditCloudAccout->text().trimmed();
    if(account.isEmpty()){
       QMessageBox::critical(this,"错误","邮箱不能为空！",QMessageBox::Ok,QMessageBox::Ok);
       return;
    }
    QString server = ui->lineEditServerAddr->text().trimmed();
    if(server.isEmpty()){
        QMessageBox::critical(this,"错误","服务器地址不能为空！",QMessageBox::Ok,QMessageBox::Ok);
        return;
    }
    NetTools *net = new NetTools;

    connect(net,SIGNAL(bindCloudAccountResult(bool,QString)),this,SLOT(bindCloudAccountResult(bool,QString)));

    QProcess p(0);
    p.start("wmic cpu get processorid");
    p.waitForStarted();
    p.waitForFinished();
    QString code;
    QStringList list = QString::fromLocal8Bit(p.readAllStandardOutput()).split("\r\r\n");
    if(list.count()>1){
        code = list.at(1);
    }
    code = code.trimmed();

    net->bindCloudAccount(account,server,code);

    ui->lineEditCloudAccout->setEnabled(false);
    ui->pushButtonBindCloudAccout->setEnabled(false);
    ui->pushButtonOk->setEnabled(false);
    ui->lineEditServerAddr->setEnabled(false);
    ui->pushButtonTestServer->setEnabled(false);

}

void FirstStartDialog::on_pushButtonOk_clicked()
{
    QString mainPass = ui->lineEditMainPass->text();
    if(mainPass.isEmpty()){
        QMessageBox::critical(this,"错误","主密码不能为空！",QMessageBox::Ok,QMessageBox::Ok);
        return;
    }
    if(ui->checkBoxUseSky->isChecked()){
        //选择了使用云服务
        QString serverAddr = ui->lineEditServerAddr->text();
        if(serverAddr.isEmpty()){
            QMessageBox::critical(this,"错误","服务器地址不能为空！",QMessageBox::Ok,QMessageBox::Ok);
            return;
        }
        if(ui->lineEditCloudAccout->isEnabled()){
            QMessageBox::critical(this,"错误","使用云服务必须绑定邮箱！",QMessageBox::Ok,QMessageBox::Ok);
            return;
        }
//        query.prepare("update sys_setting set cloudAccount=:cloudAccount,"
//                      "cloudServerAddress=:cloudServerAddress,cloudServerPort=:cloudServerPort,firstStart=:firstStart");
//        query.bindValue(":cloudAccount",ui->lineEditCloudAccout->text());
//        query.bindValue(":cloudServerAddress",ui->lineEditServerAddr->text());
//        query.bindValue(":cloudServerPort","8080");
//        query.bindValue(":firstStart","N");
//        query.exec();
//        query.clear();
    }
    QString s = QString(QCryptographicHash::hash(mainPass.toUtf8(),QCryptographicHash::Sha256).toHex());
    QSettings setting;
    setting.setValue("app/mainpass",s);
    setting.setValue("app/firstStart","N");


    Dbtools *db = new Dbtools;
//    query.prepare("update sys_setting set mainpass=:mainpass");
//    query.bindValue(":mainpass",s);
//    query.exec();

    LoginWindow *login = new LoginWindow(db);
    login->show();
    close();
}

void FirstStartDialog::on_pushButtonCancel_clicked()
{
    close();
}

void FirstStartDialog::bindCloudAccountResult(bool b, QString s)
{
    if(b){
        //绑定成功
        ui->labelCloudAccountMsg->setText(QString("<span style='color:green;'>云账号绑定成功!").append("</span>"));
        QSettings settings;
        settings.setValue("cloud/account",ui->lineEditCloudAccout->text().trimmed());
        settings.setValue("cloud/activation","Y");
        settings.setValue("cloud/serverAddr",ui->lineEditServerAddr->text().trimmed());
        ui->pushButtonOk->setEnabled(true);


    }else{
        //绑定失败
        ui->labelCloudAccountMsg->setText(QString("<span style='color:red;'>").append(s).append("</span>"));
        ui->lineEditCloudAccout->setEnabled(true);
        ui->lineEditServerAddr->setEnabled(true);
        ui->pushButtonBindCloudAccout->setEnabled(true);

    }
}

void FirstStartDialog::testServerResult(bool b, QString s)
{
    if(b){
        ui->labelServerMsg->setText("<span style='color:green;'>服务器可用!</span>");

    }else{
        ui->labelServerMsg->setText(QString("<span style='color:red;'>服务器不可用:").append(s).append("</span>"));
    }
}
